package com.yisu.auction.ewf.common.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.List;

/**
 * QuoteFieldNames———-输出key时是否使用双引号,默认为true
 WriteMapNullValue——–是否输出值为null的字段,默认为false
 WriteNullNumberAsZero—-数值字段如果为null,输出为0,而非null
 WriteNullListAsEmpty—–List字段如果为null,输出为[],而非null
 WriteNullStringAsEmpty—字符类型字段如果为null,输出为”“,而非null
 WriteNullBooleanAsFalse–Boolean字段如果为null,输出为false,而非null
 */
public class FastJson {

    public static final Logger logger = LoggerFactory.getLogger(FastJson.class);

    public static final SerializeConfig mapping = new SerializeConfig();

    public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

    static {
        mapping.put(Date.class, new SimpleDateFormatSerializer(DEFAULT_DATE_FORMAT));
    }

    public static <T> String toJson(T t) {
        return JSON.toJSONString(t, mapping, SerializerFeature.WriteMapNullValue,
                                 SerializerFeature.WriteNullNumberAsZero,
                                 SerializerFeature.WriteNullStringAsEmpty);
    }

    public static <T> T fromJson(String json,Class<T> t) {
        if (StringUtils.isBlank(json)) {
            return null;
        }
        return (T) JSON.parseObject(json, t);
    }

    public static JSONObject fromJson(String json) {
        if (StringUtils.isBlank(json)) {
            return null;
        }

        return JSON.parseObject(json);
    }


    public static <T> List<T> jsonToList(String json,Class<T> t) {
        return (List<T>) JSON.parseArray(json, t);
    }

    public static JSONArray jsonToList(String json) {
        return JSON.parseArray(json);
    }



    public static JSONObject fromJsonQuiet(String json) {
        if (StringUtils.isBlank(json)) {
            return null;
        }
        try {
            return JSON.parseObject(json);
        } catch (Exception e) {
            logger.error("", e);
            return null;
        }
    }

    public static <T> T fromJsonQuiet(String json,Class<T> t) {
        if (StringUtils.isBlank(json)) {
            return null;
        }
        try {
            return (T) JSON.parseObject(json, t);
        } catch (Exception e) {
            logger.error("", e);
            return null;
        }
    }
}
